package com.zzyl.framework.interceptor;

import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.core5.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //得到请求路径
        String url = request.getRequestURI();
        log.info("请求了路径：{}", url);
        //如果不是controller中的方法，则直接放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //从请求头获取令牌
        String headerToken = request.getHeader("authorization");
        //判断是否不为null且长度大于0，不是则
        if (!StringUtils.hasLength(headerToken)){
            log.info("-----------------------------TokenInterceptor-请求头为空，拦截------------------------------");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        try {
            //解析令牌
            Claims claims = tokenService.parseToken(headerToken);
            //获取用户id
            Long userId = claims.get("userId", Long.class);
            //保存线程变量
             UserThreadLocal.set(userId);
            log.info("-----------------------------TokenInterceptor-解析成功，放行------------------------------");
            return true;
        } catch (Exception e) {
            log.error("解析token失败", e);
            //如果解析失败，响应 401
            //response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
